<script setup name="EnergyAnalysis">
import dayjs from 'dayjs';
import { merge, map } from 'lodash-es';
import { useMain } from '@/store/app.js';
import { useWatch, useRequest } from '@/hooks';
import { getEngTypesByCode, entEngChartData, getEngJCTrend, energyConsumptionRanking, getType2 } from '@/api/index.js';
import { basicLineYAxis } from '@/components/chart/options/baseOptions.js';
import { barSeriesItem, lineSeriesItem, usePickerOption } from '@/views/hooks.js';
import { useDSECRatio, useEnergyCRatio } from '@/views/orgMgmt/hooks.js';
import AreaForm from '@/views/components/AreaForm.vue';
import DateChart from '@/views/components/DateChart.vue';

const { proxy } = getCurrentInstance();
const { projectType } = useMain();
const TGColor = ['#26d5d5', '#4992ff', '#eda422', '#f53019', '#5afe5d', '#f58819', '#fe5a5a', '#d5d526'];
const JCColor = ['#4992ff', '#ee6666', '#eda422', '#5afe5d'];

const rangeType = ref({
  d: {
    type: 'daterange',
    fmt: 'yyyy-MM-dd',
    default: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().subtract(1, 'day').format('YYYY-MM-DD')],
    pickerOptions: usePickerOption('d'),
  },
  m: {
    type: 'monthrange',
    fmt: 'yyyy-MM',
    default: [dayjs().subtract(6, 'month').format('YYYY-MM'), dayjs().subtract(1, 'month').format('YYYY-MM')],
    pickerOptions: usePickerOption('m'),
  },
  y: {
    type: 'year',
    fmt: 'yyyy',
    default: [dayjs().subtract(2, 'year').format('YYYY'), dayjs().format('YYYY')],
  },
});
const inId = ref('');
const radio = ref(projectType);
const contractTypeCode = ref('');
const energyType = ref('');
const energyType2 = ref('');
const reset = ref(0);
const engUnit = ref('tce');
const dateParams = ref(null);
const dateParams2 = ref(null);
const dateRangeEC = ref(rangeType.value.d.default);
const yearRangeEC = ref({ sYear: null, eYear: null });
const ECParams = ref({
  dateType: 'd',
  dateStart: dateRangeEC.value[0],
  dateEnd: dateRangeEC.value[1],
});
const chartRef = ref(null);
const chartRef2 = ref(null);
const chartRef3 = ref(null);
const chartOpts = ref({
  color: [],
  grid: { bottom: 30, top: 50, left: 10, right: 10 },
  yAxis: [
    { name: '单位：tce' },
    merge({}, basicLineYAxis, {
      name: '单位：%',
      nameTextStyle: { fontSize: 12, align: 'right' },
    }),
  ],
  // tooltip: {
  //   formatter: params => {
  //     if (params.length > 0) {
  //       let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
  //       forEach(params, e => {
  //         let seriesName = e.seriesName;
  //         let value = e.value[e.dimensionNames[e.encode.y]] ?? '-';
  //         if (includes(seriesName, '环比') || includes(seriesName, '同比')) {
  //           const ratio = Number(e.value[e.dimensionNames[e.encode.y]]);
  //           const sign = Math.sign(ratio);
  //           value =
  //             ratio !== 0
  //               ? `<span>${value}%</span><span class="u-ml5 u-fw-b ${sign > 0 ? 'u-red">↑' : 'u-green">↓'}</span>`
  //               : `${value}%`;
  //         }
  //         str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30 u-df-st">${value}</li></ul>`;
  //       });
  //       return str;
  //     }
  //     return '';
  //   },
  // },
  dataset: {
    // dimensions: [],
    // source: [],
  },
  series: [],
});
const gradientList = [
  ['rgba(255, 255, 255, 0)', '#3fcfd1'],
  ['rgba(255, 255, 255, 0)', '#64c103'],
  ['rgba(255, 255, 255, 0)', '#deb302'],
];
const [engTypeList, , runEngType] = useRequest(getEngTypesByCode, {
  manual: true,
  onSuccess: res => {
    engUnit.value = res.data[0]?.energyUnit;
    chartOpts.value.yAxis[0].name = `单位：${res.data[0]?.energyUnit}`;
    energyType.value = res?.data?.[0]?.id;
    if (radio.value === 'TG') {
      searchTG();
    } else {
      searchJC();
    }
    energyType2.value = res?.data?.[0]?.id;
    runRank({ ...ECParams.value, inId: inId.value, projectType: radio.value, energyType: energyType2.value });
  },
});
// const [engTypeList2, , runType] = useRequest(getType2, {
//   onSuccess: res => {
//     energyType2.value = res?.[0]?.id;
//     runRank({ ...ECParams.value, inId: inId.value, projectType: radio.value, energyType: energyType2.value });
//   },
// });
const [, TGLoading, runTG] = useRequest(entEngChartData, {
  manual: true,
  onSuccess: res => {
    chartOpts.value.color = TGColor;
    if (contractTypeCode.value === 'CONVENTION') {
      chartOpts.value.dataset.dimensions = [
        'energyValueDate',
        { name: 'energyBasisValue', displayName: '基准能耗' },
        { name: 'energyConsumeValue', displayName: '实际能耗' },
      ];
    } else if (contractTypeCode.value === 'SHARE' || contractTypeCode.value === 'ENSURE') {
      chartOpts.value.dataset.dimensions = [
        'energyValueDate',
        { name: 'energyBasisValue', displayName: '基准能耗' },
        { name: 'energyConsumeValue', displayName: '实际能耗' },
        { name: 'energyConsumeValueRatio', displayName: '实际能耗环比' },
      ];
    }
    chartOpts.value.dataset.source = res?.data ?? [];
    chartOpts.value.series = Array.from({ length: chartOpts.value.dataset.dimensions?.length - 1 }, (_, i) => {
      return i === 0
        ? merge({}, barSeriesItem, { yAxisIndex: 0 })
        : merge({}, lineSeriesItem, { yAxisIndex: i < 2 ? 0 : 1 });
    });
  },
});
const [, JCLoading, runJC] = useRequest(getEngJCTrend, {
  manual: true,
  onSuccess: res => {
    chartOpts.value.color = JCColor;
    chartOpts.value.dataset.source = map(res.data, v => ({ ...v, trend: v.thisValue }));
    if (dateParams.value.dateType == 'm') {
      chartOpts.value.dataset.dimensions = [
        'date',
        { name: 'thisValue', displayName: '能耗量' },
        { name: 'trend', displayName: '能耗趋势' },
        { name: 'chainValue', displayName: '环比' },
        { name: 'togetherValue', displayName: '同比' },
      ];
    }
    if (dateParams.value.dateType == 'y') {
      chartOpts.value.dataset.dimensions = [
        'date',
        { name: 'thisValue', displayName: '能耗量' },
        { name: 'trend', displayName: '能耗趋势' },
        { name: 'chainValue', displayName: '环比' },
      ];
    }
    if (dateParams.value.dateType == 'd') {
      chartOpts.value.dataset.dimensions = [
        'date',
        { name: 'thisValue', displayName: '能耗量' },
        { name: 'trend', displayName: '能耗趋势' },
        { name: 'chainValue', displayName: '环比' },
      ];
    }
    chartOpts.value.series = Array.from({ length: chartOpts.value.dataset.dimensions?.length - 1 }, (_, i) => {
      return i === 0
        ? merge({}, barSeriesItem, { yAxisIndex: 0 })
        : merge({}, lineSeriesItem, { yAxisIndex: i < 2 ? 0 : 1 });
    });
  },
});
const [rankData, loadingR, runRank] = useRequest(energyConsumptionRanking, {
  manual: true,
});
// 开始时间不能大于结束时间
const disabledDateStartEC = ref({
  disabledDate: time => {
    if (yearRangeEC.value.eYear) {
      return (
        dayjs(time) > dayjs(yearRangeEC.value.eYear) || dayjs(time) < dayjs(yearRangeEC.value.eYear).subtract(2, 'year')
      );
    }
  },
});
const disabledDateEC = ref({
  disabledDate: time => {
    return dayjs(time) < dayjs(yearRangeEC.value.sYear) || dayjs(time) > dayjs(yearRangeEC.value.sYear).add(2, 'year');
  },
});
const [ratioParams, extraPieOpts, ratioLoading, handleRatioDate] = useDSECRatio(rangeType);
const [ratioParams2, extraPieOpts2, ratioLoading2, handleRatioDate2] = useEnergyCRatio(rangeType);
const searchTG = () => {
  runTG({
    contractType: contractTypeCode.value,
    energyType: energyType.value,
    projectType: radio.value,
    inId: inId.value,
    dateType: dateParams.value.dateType,
    dateStart: dateParams.value.startTime,
    dateEnd: dateParams.value.endTime,
  });
};
const searchJC = () => {
  runJC({
    istco2e: false,
    energyType: energyType.value,
    projectType: radio.value,
    inId: inId.value,
    dateType: dateParams.value.dateType,
    dateStart: dateParams.value.startTime,
    dateEnd: dateParams.value.endTime,
  });
};
const handleQuery = queryParams => {
  inId.value = queryParams?.buildingCode?.enterpriseCode;
  ratioParams.value.buildingCode = inId.value;
  ratioParams.value.dateType = dateParams2.value.dateType;
  ratioParams.value.dateStart = dateParams2.value.startTime;
  ratioParams.value.dateEnd = dateParams2.value.endTime;
  ratioParams2.value.inId = inId.value;
  contractTypeCode.value = queryParams?.contractTypeCode;
  // runType();
  runEngType({ enterpriseCode: inId.value, projectType: radio.value, allType: true });
};
const resetQuery = queryParams => {
  ratioParams2.value.projectType = radio.value;
};
const handleChart = dateParams => {
  dateParams.value = dateParams;
  if (dateParams.startTime && dateParams.endTime) {
    if (radio.value === 'TG') {
      searchTG();
    } else {
      searchJC();
    }
  }
};
const handleChange = val => {
  if (radio.value === 'TG') {
    searchTG();
  } else {
    searchJC();
  }
};
const handleChange2 = val => {
  runRank({ ...ECParams.value, inId: inId.value, projectType: radio.value, energyType: energyType2.value });
};
const changeType = item => {
  chartOpts.value.yAxis[0].name = `单位：${item?.energyUnit ?? ''}`;
};
const handleECDaterange = val => {
  ECParams.value.dateStart = val?.[0] ?? null;
  ECParams.value.dateEnd = val?.[1] ?? null;
  runRank({ ...ECParams.value, inId: inId.value, projectType: radio.value, energyType: energyType2.value });
};
const handleECYearrange = () => {
  ECParams.value.dateStart = yearRangeEC.value.sYear;
  ECParams.value.dateEnd = yearRangeEC.value.eYear;
  runRank({ ...ECParams.value, inId: inId.value, projectType: radio.value, energyType: energyType2.value });
};
const radioChange = val => {
  ECParams.value.dateType = val;
  if (val !== 'y') {
    dateRangeEC.value = rangeType.value[val].default;
    ECParams.value.dateStart = dateRangeEC.value[0];
    ECParams.value.dateEnd = dateRangeEC.value[1];
  } else {
    yearRangeEC.value.sYear = rangeType.value.y.default[0];
    yearRangeEC.value.eYear = rangeType.value.y.default[1];
    ECParams.value.dateStart = yearRangeEC.value.sYear;
    ECParams.value.dateEnd = yearRangeEC.value.eYear;
  }
  runRank({ ...ECParams.value, inId: inId.value, projectType: radio.value, energyType: energyType2.value });
};
useWatch(
  radio,
  n => {
    reset.value = reset.value + 1;
  },
  { immediate: true },
);
onMounted(() => {
  dateParams.value = chartRef.value.dateParams;
  dateParams2.value = chartRef2.value.dateParams;
  ratioParams2.value.dateType = chartRef3.value.dateParams.dateType;
  ratioParams2.value.dateStart = chartRef3.value.dateParams.startTime;
  ratioParams2.value.dateEnd = chartRef3.value.dateParams.endTime;
  ratioParams2.value.projectType = radio.value;
});
useWatch(
  () => proxy.$store.state.global.setting.sideTheme,
  n => {
    if (n === 'theme-dark') {
      extraPieOpts2.value.title.textStyle.rich.a.color = '#fff';
      extraPieOpts2.value.legend.textStyle.rich.a.color = '#fff';
      extraPieOpts2.value.legend.textStyle.rich.c.color = '#fff';
    } else {
      extraPieOpts2.value.title.textStyle.rich.a.color = '#303133';
      extraPieOpts2.value.legend.textStyle.rich.a.color = '#303133';
      extraPieOpts2.value.legend.textStyle.rich.c.color = '#303133';
    }
  },
  { immediate: true },
);
</script>
<template>
  <div class="app-container">
    <div class="u-df-st u-base-fg u-pl20 u-mb20">
      <el-radio-group v-model="radio" size="small" class="radio">
        <el-radio-button label="JC">监测机构</el-radio-button>
        <el-radio-button label="TG">托管机构</el-radio-button>
      </el-radio-group>
      <AreaForm
        ref="areaFormRef"
        :projectType="radio"
        :reset="reset"
        :propParams="true"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
        :isStage="true"
        :showType="radio === 'TG' ? true : false"
        style="margin-bottom: 0px"
      />
    </div>
    <div class="u-base-fg u-p20 u-mb20" style="height: 380px; position: relative">
      <span style="position: absolute; top: 20px">能耗趋势分析</span>
      <el-select
        v-model="energyType"
        :clearable="false"
        placeholder="请选择"
        style="width: 100px; position: absolute; top: 20px; right: 400px"
        @change="handleChange"
        size="mini"
      >
        <el-option
          v-for="item in engTypeList"
          :key="item.id"
          :label="item.energyName + '能耗'"
          :value="item.id"
          @click.native="changeType(item)"
        ></el-option>
      </el-select>
      <DateChart
        v-loading="JCLoading | TGLoading"
        ref="chartRef"
        formStyle="u-df-ed"
        style="height: 340px; width: 100%"
        :extraOpts="chartOpts"
        @handleDateParams="handleChart"
        :mergeDefault="false"
      />
    </div>
    <el-row type="flex" :gutter="20">
      <el-col :span="8">
        <div class="grid-content u-base-fg">
          <div class="u-fs16 u-mb10">各项能源能耗占比</div>
          <DateChart
            v-loading="ratioLoading2"
            ref="chartRef3"
            style="height: 320px; width: 100%"
            :type="'pie'"
            :extraOpts="extraPieOpts2"
            @handleDateParams="handleRatioDate2"
            :mergeDefault="false"
          />
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content u-base-fg">
          <div class="u-fs16 u-mb10">区域能耗排名</div>
          <el-form :model="ECParams" :inline="true" class="u-df-spb qynh-form">
            <el-form-item>
              <el-select
                v-model="energyType2"
                :clearable="false"
                placeholder="请选择"
                style="width: 100px"
                @change="handleChange2"
                size="mini"
              >
                <el-option
                  v-for="item in engTypeList"
                  :key="item.id"
                  :label="item.energyName + '能耗'"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="rangeType[ECParams.dateType].type !== 'year'">
              <el-date-picker
                v-model="dateRangeEC"
                :type="rangeType[ECParams.dateType].type ?? 'daterange'"
                :key="rangeType[ECParams.dateType].type ?? 'daterange'"
                :value-format="rangeType[ECParams.dateType].fmt ?? 'yyyy-MM-dd'"
                :picker-options="rangeType[ECParams.dateType].pickerOptions"
                :clearable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
                align="left"
                style="width: 240px"
                @change="handleECDaterange"
              />
            </el-form-item>
            <el-form-item v-else>
              <el-date-picker
                v-model="yearRangeEC.sYear"
                :picker-options="disabledDateStartEC"
                :clearable="false"
                type="year"
                value-format="yyyy"
                placeholder="开始年份"
                size="mini"
                style="width: 115px"
                class="u-mr5"
                @change="handleECYearrange"
              />
              <el-date-picker
                v-model="yearRangeEC.eYear"
                :picker-options="disabledDateEC"
                :clearable="false"
                type="year"
                value-format="yyyy"
                placeholder="结束年份"
                size="mini"
                style="width: 115px"
                @change="handleECYearrange"
              />
            </el-form-item>
            <el-form-item prop="dateType" class="u-df-ct">
              <el-radio-group v-model="ECParams.dateType" size="mini" @input="radioChange">
                <el-radio-button label="d">日</el-radio-button>
                <el-radio-button label="m">月</el-radio-button>
                <el-radio-button label="y">年</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <ul v-if="rankData?.length > 0" v-loading="loadingR" class="u-fs12 eng-summary-list">
            <li v-for="(item, idx) in rankData ?? []" :key="item.key">
              <div class="u-df-spb">
                <span>
                  {{ idx + 1 }}
                  <span class="u-ml5">{{ item?.key ?? '-' }}</span>
                </span>
                <span>
                  {{ item?.value1 ?? '-' }}
                  <span class="u-sec-text">{{ item?.value2 ?? '-' }}</span>
                </span>
              </div>
              <div class="u-border">
                <div
                  class="u-h100"
                  :style="{
                    width: `${item.value3}%`,
                    background: gradientList[idx]
                      ? `linear-gradient(90deg, ${gradientList[idx][0]} 0%, ${gradientList[idx][1]} 100%)`
                      : '',
                  }"
                ></div>
              </div>
            </li>
          </ul>
          <el-empty v-else v-loading="loadingR" :image-size="1"></el-empty>
          <!-- <DateChart
            v-loading="loading4"
            ref="chartRef4"
            style="height: 360px; width: 100%"
            :type="'pie'"
            :extraOpts="extraPieOpts"
            @handleDateParams="handleChart4"
            :mergeDefault="false"
          /> -->
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content u-base-fg">
          <div class="u-fs16 u-mb10">设备系统用电能耗占比</div>
          <DateChart
            v-loading="ratioLoading"
            ref="chartRef2"
            style="height: 320px; width: 100%"
            :type="'pie'"
            :extraOpts="extraPieOpts"
            @handleDateParams="handleRatioDate"
            :mergeDefault="false"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  height: 400px;
  padding: 20px;
}

.qynh-form ::v-deep .el-form-item {
  margin-bottom: 0;
  margin-right: 0 !important;
  display: flex;
  justify-content: flex-start;
  align-items: center;

  .el-form-item__content {
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 28px;
  }
}

::v-deep .el-radio-button--mini .el-radio-button__inner {
  padding: 6px 8px;
  height: 28px !important;
  margin-right: 3px;
  border-radius: 0;
}

.u-border {
  width: 100%;
  height: 2px;
  margin: 5px 0 10px;
  background-color: rgba(255, 255, 255, 0.2);
}

.eng-summary-list {
  height: calc(100% - 60px);
  padding-top: 20px;
  overflow-y: auto;
}
</style>
